import axios from 'axios';
import { nanoid } from 'nanoid';
window._axios_cancel_funs = [];
const Ins = axios.create({
  timeout: 5000,
  baseURL: '',
  withCredentials: false,
});

Ins.interceptors.request.use((config) => {
  const id = nanoid();
  config = {
    ...config,
    headers: {
      token: 'xx',
    },
    cancelToken: new axios.CancelToken(function (cancel) {
      window._axios_cancel_funs.push({ cancel, id });
    }),
    id: id,
  };

  return config;
});

Ins.interceptors.response.use((response) => {
  const id = response.config.id;
  const index = window._axios_cancel_funs.findIndex((k) => k.id === id);
  window._axios_cancel_funs.splice(index, 1);
  return response;
});
const get = (url = '', params = {}) => {
  return new Promise((resolve, reject) => {
    Ins.get(url, { params: params })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
const post = (url = '', data = {}) => {
  return new Promise((resolve, reject) => {
    Ins.post(url, data)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const cancelAllRequest = () => {
  while (window._axios_cancel_funs.length) {
    window._axios_cancel_funs.pop().cancel();
  }
};
export { get, post };
